/**  
*  Doku2Buddy - A DokuWiki to BuddyPress Wiki-Component Converter
*  Copyright (C) 2010 Skye Book
*  
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation, either version 3 of the License, or
*  (at your option) any later version.
*  
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*  
*  You should have received a copy of the GNU General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package com.sbook.d2b;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;

import com.sbook.d2b.db.DBManager;
import com.sbook.d2b.formatting.BuddyPressArticle;
import com.sbook.d2b.formatting.BuddyPressFormatter;
import com.sbook.d2b.formatting.DokuInterpreter;

/**
 * Takes input from the main class (or GUI) and triggers the various
 * steps in the conversion.
 * @author Skye Book
 *
 */
public class ConversionCatalyst {
	private DBManager dbMan;
	private DokuInterpreter dokuInterp;

	/**
	 * 
	 */
	public ConversionCatalyst(File dokupath, String dokuURL, String dbName, String dbUser, char[] dbPass, String dbHost, int dbPort, String bpGroup) {
		readDoku(dokupath, dokuURL);
		
		startDBManager(dbUser, dbPass, dbName, dbHost, dbPort);
		
		BuddyPressFormatter bpf = new BuddyPressFormatter(dokuInterp.getArticles(), dbMan, "oldwikiuser",  bpGroup);
		
		ArrayList<Integer> insertedArticles = new ArrayList<Integer>();
		Iterator<BuddyPressArticle> itA = bpf.getArticles().iterator();
		while(itA.hasNext()){
			int articleID = dbMan.insertArticle(itA.next());
			if(articleID!=-1){
				insertedArticles.add(articleID);
			}
		}
		System.out.println(insertedArticles.size() + " articles added");
		
		// add them to the wiki entries
		// TODO:  Change the way we decide groupID's
		dbMan.updateGroupWikiEntries(bpGroup, insertedArticles);
		
		System.out.println("Finished!");
	}
	
	private void readDoku(File dokupath, String dokuURL){
		dokuInterp = new DokuInterpreter(dokupath, dokuURL);
	}
	
	private void startDBManager(String dbUser, char[] dbPass, String dbName, String dbHost, int dbPort){
		String pass="";
		// zeroes out the password array as it is read.
		for(int i=0; i<dbPass.length; i++){
			pass+=dbPass[i];
			dbPass[i]=0;
		}
		
		// Open the database connection.
		dbMan = new DBManager(dbUser, pass, dbName, dbHost, dbPort, "http://localhost/wordpress");
		
		// nulls the complete password
		pass=null;
	}
}
